<template>
  <a-popover :visible="qrcodeVisible">
    <a-button class="mr12" @click="showQrcode">
      {{ title }}
    </a-button>
    <div slot="title" class="pv8">登记二维码</div>
    <div slot="content">
      <div id="qrbox" class="p8" style="width: 216px; height: 216px;display: flex;align-items: center;justify-content: center;">
        <a-spin tip="加载中" v-if="loading"> </a-spin>
        <img v-else :src="imgUrl" width="100%" height="100%" />

        <!-- <div id="qrcode" /> -->
      </div>
      <div class="mv12 fs12" style="color: #a6a8b4; width: 216px">
        <span style="color: red">* </span>
        保存二维码，分享到微信，长按识别录入信息，或者直接微信扫码录入
      </div>
      <div class="mt12" style="display: flex; justify-content: center">
        <a-space>
          <a-button type="primary" size="small" @click="onGetDownload">保存</a-button>
          <a-button type="default" size="small" @click="qrcodeVisible = false">取消</a-button>
        </a-space>
      </div>
    </div>
  </a-popover>
</template>
<script>
import axios from "axios";
import { getToken } from "xqjr-module-auth";
import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";
import { mapState } from "vuex";
import { getGenerateSalaryQRCode } from "./api";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {
    title: {
      type: String,
      default: ""
    },
    needBatch: {
      type: Boolean,
      default: true
    },
    showFunc: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      qrcodeVisible: false,
      qrcodeGened: false,
      loading: false,
      imgUrl: ""
    };
  },
  computed: {
    ...mapState(["auth"]),
    siteId() {
      const siteList = this.auth && this.auth.permissions && this.auth.permissions.siteList ? this.auth.permissions.siteList : [];
      const currSite = siteList.find(item => item.currSite);
      return currSite ? currSite.id : null;
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    showQrcode() {
      if (this.qrcodeVisible) {
        return false;
      }
      if (this.needBatch) {
        const info = this.showFunc();
        if (info) {
          if (this.siteId) {
            this.qrcodeVisible = true;
            this.generateCode(info);
            return false;
          }
        }
        this.$message.warning("二维码生成遇到问题，请稍后重试");
      } else {
        this.qrcodeVisible = true;
        this.generateCode();
        return false;
      }
    },
    generateCode(info) {
      if (!this.qrcodeGened) {
        this.onGetGenerateSalaryQRCode(info);
        // const host = process.env.VUE_APP_H5;
        // const link = info
        //   ? `${host}/#/?siteId=${this.siteId}&batchId=${info.batchId}&batchType=${info.batchType}`
        //   : `${host}/#/?siteId=${this.siteId}`;

        // this.$nextTick(() => {
        //   this.genQrcode(link, "qrcode");
        //   this.qrcodeGened = true;
        // });
      }
    },
    async onGetGenerateSalaryQRCode(info) {
      this.loading = true;
      try {
        const { data } = await getGenerateSalaryQRCode({
          siteId: this.siteId,
          batchId: info ? info.batchId : null,
          batchType: info ? info.batchType : null
        });
        this.imgUrl = data;
        this.qrcodeGened = true;
        this.loading = false;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    // 生成二维码
    genQrcode(extendLink, idName) {
      new QRCode(idName, {
        width: 200,
        height: 200, // 高度
        text: extendLink // 二维码内容
      });
    },
    // 下载
    saveQrcode() {
      html2canvas(document.getElementById("qrbox"), {
        useCORS: true,
        allowTaint: false
      }).then(canvas => {
        const MIME_TYPE = "image/png";
        const imgURL = canvas.toDataURL("image/png");
        const link = document.createElement("a");
        link.download = `登记二维码`;
        link.href = imgURL;
        link.dataset.downloadurl = [MIME_TYPE, link.download, link.href].join(":");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    },
    onGetDownload() {
      const url = this.imgUrl;
      const name = "登记二维码";
      axios({
        url: "/recruit2/api/v1/talentPools/downloadOss",
        method: "get",
        params: {
          url
        },
        responseType: "blob",
        headers: {
          token: getToken()
        }
      })
        .then(res => {
          if (res.data) {
            const rspHeaders = res.headers;
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            if (rspHeaders["content-disposition"]) {
              try {
                const fileName = decodeURI(
                  rspHeaders["content-disposition"]
                    .split(";")[1]
                    .split("=")[1]
                    .replaceAll('"', "")
                );
                const fileNameArr = fileName.split(".");
                link.download = name + "." + fileNameArr[1];
                link.click();
                URL.revokeObjectURL(link.href);
                document.body.removeChild(link);
              } catch (err) {
                console.log("error log --> ", err);
              }
            } else {
              this.$notification.error({ message: "下载失败" });
            }
          }
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    }
  }
};
</script>
<style lang="scss"></style>
